jQuery(function($){
			
	//handling tabs and loading/displaying relevant messages and forms
	//not needed if using the alternative view, as described in docs
	$('#inbox-tabs a[data-toggle="tab"]').on('show.bs.tab', function (e) {
		var currentTab = $(e.target).data('target');
		if(currentTab == 'write') {//写邮件
			Inbox.show_form();
		}
		else if(currentTab == 'sent') {//已发送
			Inbox.show_list();
		}
	})

	
	//basic initializations
	$('.message-list .message-item input[type=checkbox]').removeAttr('checked');
	$('.message-list').on('click', '.message-item input[type=checkbox]' , function() {
		$(this).closest('.message-item').toggleClass('selected');
		if(this.checked) Inbox.display_bar(1);//display action toolbar when a message is selected
		else {
			Inbox.display_bar($('.message-list input[type=checkbox]:checked').length);
			//determine number of selected messages and display/hide action toolbar accordingly
		}
	});


	//check/uncheck all messages
	$('#id-toggle-all').removeAttr('checked').on('click', function(){
		if(this.checked) {
			Inbox.select_all();
		} else Inbox.select_none();
	});
	
	//select all
	$('#id-select-message-all').on('click', function(e) {
		e.preventDefault();
		Inbox.select_all();
	});
	
	//select none
	$('#id-select-message-none').on('click', function(e) {
		e.preventDefault();
		Inbox.select_none();
	});
	
	//select read
	$('#id-select-message-read').on('click', function(e) {
		e.preventDefault();
		Inbox.select_read();
	});

	//select unread
	$('#id-select-message-unread').on('click', function(e) {
		e.preventDefault();
		Inbox.select_unread();
	});


	/**
	 * 点击邮件主题，在新的标签页显示详情信息
	 * @returns
	 */
	$('.message-list .message-item .text').on('click', function() {
		
		//show the loading icon
		$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
		
		$('.message-inline-open').removeClass('message-inline-open').find('.message-content').remove();

		var message_list = $(this).closest('.message-list');

		$('#inbox-tabs a[href="#sent"]').parent().removeClass('active');

		//将邮件内容添加到详情页面
		var dom = $(this).parent().parent();
		var id = dom.find('span[class=hidden]').html();
		var toUsername = dom.find('span[class=sender]').html();
		var time = dom.find('span[class=time]').attr('title');
		var subject = dom.children('span[class=summary]').children('span[class=text]').html();
		var content = dom.find('span[class=\'hidden content\']').text();
		var attachmentIds = dom.find('span[class=\'hidden attachmentIds\']').text();
		
		var detailHeader = $('#id-message-content .message-header');
		detailHeader.find('span[class=\'hidden email-id\']').html(id);
		detailHeader.find('a[class=sender]').html(toUsername);
		detailHeader.find('span[class=\'time grey\']').html(time);
//		$('#id-message-item-navbar .messagebar-item-right span[class=grey]').html(time);
		detailHeader.find('span[class=\'blue bigger-125 email-subject\']').html(subject);
		$('#id-message-content .message-body').html(content);
//		$('#id-message-content .message-body').trigger("create");
		if(attachmentIds != null && attachmentIds.trim() != ''){
			appendAttachment(attachmentIds);
		}
		
		//some waiting
		setTimeout(function() {
			//hide everything that is after .message-list (which is either .message-content or .message-form)
			message_list.next().addClass('hide');
			$('.message-container').find('.message-loading-overlay').remove();

			//close and remove the inline opened message if any!

			//hide all navbars
			$('.message-navbar').addClass('hide');
			//now show the navbar for single message item
			$('#id-message-item-navbar').removeClass('hide');

			//hide all footers
			$('.message-footer').addClass('hide');
			//now show the alternative footer
			$('.message-footer-style2').removeClass('hide');
			
			//move .message-content next to .message-list and hide .message-list
			$('.message-content').removeClass('hide').insertAfter(message_list.addClass('hide'));

			//在邮件详情部分添加滚动条，暂时屏蔽
//			$('.message-content .message-body').ace_scroll({
//				size: 150,
//				mouseWheelLock: true,
//				styleClass: 'scroll-visible'
//			});

		}, 500 + parseInt(Math.random() * 500));
	});
	
	/**
	 * 循环添加附件列表信息，支持附件下载
	 */
	function appendAttachment(ids){
		$('#att-title-text').html('附件');
		$('#id-message-content').find('ul[class=\'attachment-list pull-left list-unstyled\']').html('');
		//查询附件信息后写入页面
		$.ajax({
			url: '/admin/sys/attachment/selectByIds',
			data: {'ids': ids},
			type: 'POST',
			dataType: 'JSON',
			success: function(obj){
				if(obj.status == 200){
					for(var i = 0; i < obj.data.length; i++){
						$('#id-message-content').find('ul[class=\'attachment-list pull-left list-unstyled\']').append(
								'<li>\
								<i class="ace-icon fa fa-file-o bigger-110"></i>\
								<span class="attached-name" title="' + obj.data[i].originName + '">' + obj.data[i].originName + '</span>\
								&nbsp;(' + obj.data[i].fileSize + ')\
								<span class="action-buttons">\
								&nbsp;<a href="' + obj.data[i].relativePath + '" download="' + obj.data[i].originName + '" onclick="setDownloadCount(\''+obj.data[i].id+'\',\''+obj.data[i].downloadCounts+'\')">\
								<i class="ace-icon fa fa-download bigger-125 blue"></i>\
								</a>\
								</span>\
						</li>');
					}
				}
			}
		});
	}
	
	//点击邮件主题，在列表下方显示详情信息
	/*$('.message-list .message-item .text').on('click', function(){
		var message = $(this).closest('.message-item');

		//if message is open, then close it
		if(message.hasClass('message-inline-open')) {
			message.removeClass('message-inline-open').find('.message-content').remove();
			return;
		}

		$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
		setTimeout(function() {
			$('.message-container').find('.message-loading-overlay').remove();
			message
				.addClass('message-inline-open')
				.append('<div class="message-content" />')
			var content = message.find('.message-content:last').html( $('#id-message-content').html() );

			//remove scrollbar elements
			content.find('.scroll-track').remove();
			content.find('.scroll-content').children().unwrap();
			
			content.find('.message-body').ace_scroll({
				size: 150,
				mouseWheelLock: true,
				styleClass: 'scroll-visible'
			});
	
		}, 500 + parseInt(Math.random() * 500));
		
	});*/


	//返回发送列表
	$('.btn-back-message-list').on('click', function(e) {
		e.preventDefault();
		$('#inbox-tabs a[href="#sent"]').tab('show');
		$('#id-message-content .message-body').html('');
	});


	//hide message list and display new message form
	/**
	$('.btn-new-mail').on('click', function(e){
		e.preventDefault();
		Inbox.show_form();
	});
	*/
	
	var Inbox = {
		//displays a toolbar according to the number of selected messages
		display_bar : function (count) {
			if(count == 0) {
				$('#id-toggle-all').removeAttr('checked');
				$('#id-message-list-navbar .message-toolbar').addClass('hide');
				$('#id-message-list-navbar .message-infobar').removeClass('hide');
			}
			else {
				$('#id-message-list-navbar .message-infobar').addClass('hide');
				$('#id-message-list-navbar .message-toolbar').removeClass('hide');
			}
		}
		,
		select_all : function() {
			var count = 0;
			$('.message-item input[type=checkbox]').each(function(){
				this.checked = true;
				$(this).closest('.message-item').addClass('selected');
				count++;
			});
			
			$('#id-toggle-all').get(0).checked = true;
			
			Inbox.display_bar(count);
		}
		,
		select_none : function() {
			$('.message-item input[type=checkbox]').removeAttr('checked').closest('.message-item').removeClass('selected');
			$('#id-toggle-all').get(0).checked = false;
			
			Inbox.display_bar(0);
		}
		,
		select_read : function() {
			$('.message-unread input[type=checkbox]').removeAttr('checked').closest('.message-item').removeClass('selected');
			
			var count = 0;
			$('.message-item:not(.message-unread) input[type=checkbox]').each(function(){
				this.checked = true;
				$(this).closest('.message-item').addClass('selected');
				count++;
			});
			Inbox.display_bar(count);
		}
		,
		select_unread : function() {
			$('.message-item:not(.message-unread) input[type=checkbox]').removeAttr('checked').closest('.message-item').removeClass('selected');
			
			var count = 0;
			$('.message-unread input[type=checkbox]').each(function(){
				this.checked = true;
				$(this).closest('.message-item').addClass('selected');
				count++;
			});
			
			Inbox.display_bar(count);
		}
	}

	//显示发件列表
	Inbox.show_list = function() {
		$('.message-navbar').addClass('hide');
		$('#id-message-list-navbar').removeClass('hide');

		$('.message-footer').addClass('hide');
		$('.message-footer:not(.message-footer-style2)').removeClass('hide');

		$('.message-list').removeClass('hide').next().addClass('hide');
		//hide the message item / new message window and go back to list
	}

	//显示写邮件页面
	Inbox.show_form = function() {
		if($('.message-form').is(':visible')) return;
		if(!form_initialized) {
			initialize_form();
		}
		
		var message = $('.message-list');
		$('.message-container').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');
		
		setTimeout(function() {
			message.next().addClass('hide');
			
			$('.message-container').find('.message-loading-overlay').remove();
			
			$('.message-list').addClass('hide');
			$('.message-footer').addClass('hide');
			$('.message-form').removeClass('hide').insertAfter('.message-list');
			
			$('.message-navbar').addClass('hide');
			$('#id-message-new-navbar').removeClass('hide');
			
			//reset form??
			$('.message-form .wysiwyg-editor').empty();
		
			$('.message-form .ace-file-input').closest('.file-input-container:not(:first-child)').remove();
			$('.message-form input[type=file]').ace_file_input('reset_input');
			
			$('.message-form').get(0).reset();
			
		}, 300 + parseInt(Math.random() * 300));
	}

	//初始化“写邮件”页面
	var form_initialized = false;
	function initialize_form() {
		if(form_initialized) return;
		form_initialized = true;
		
		//富文本编辑框
		$('.message-form .wysiwyg-editor').ace_wysiwyg({
			toolbar:
				[
					'font',
					null,
					'fontSize',
					null,
					{name:'bold', className:'btn-info'},
					{name:'italic', className:'btn-info'},
					{name:'strikethrough', className:'btn-info'},
					{name:'underline', className:'btn-info'},
					null,
					{name:'insertunorderedlist', className:'btn-success'},
					{name:'insertorderedlist', className:'btn-success'},
					{name:'outdent', className:'btn-purple'},
					{name:'indent', className:'btn-purple'},
					null,
					{name:'justifyleft', className:'btn-primary'},
					{name:'justifycenter', className:'btn-primary'},
					{name:'justifyright', className:'btn-primary'},
					{name:'justifyfull', className:'btn-inverse'},
					null,
					{name:'createLink', className:'btn-pink'},
					{name:'unlink', className:'btn-pink'},
					null,
					//{name:'insertImage', className:'btn-success'},
					null,
					'foreColor',
					null,
					{name:'undo', className:'btn-grey'},
					{name:'redo', className:'btn-grey'}
				]
		}).prev().addClass('wysiwyg-style1');

		//文件上传
		$('.message-form input[type=file]').ace_file_input()
		.closest('.ace-file-input')
		.addClass('width-90 inline')
		.wrap('<div class="form-group file-input-container"><div class="col-sm-7"></div></div>');

		//添加附件，点击后增加一个文件上传的input
		$('#id-add-attachment').on('click', function(){
			var file = $('<input type="file" name="attachment[]" class="attachment[]"/>').appendTo('#form-attachments');
			file.ace_file_input();
			
			file.closest('.ace-file-input')
			.addClass('width-90 inline')
			.wrap('<div class="form-group file-input-container"><div class="col-sm-7"></div></div>')
			.parent().append('<div class="action-buttons pull-right col-xs-1">\
								<a href="#" data-action="delete" class="middle">\
									<i class="ace-icon fa fa-trash-o red bigger-130 middle"></i>\
								</a>\
							</div>')
			.find('a[data-action=delete]').on('click', function(e){
				//the button that removes the newly inserted file input
				e.preventDefault();
				$(this).closest('.file-input-container').hide(300, function(){ $(this).remove() });
			});
		});
	}//initialize_form

	//turn the recipient field into a tag input field!
	/**	
	var tag_input = $('#form-field-recipient');
	try { 
		tag_input.tag({placeholder:tag_input.attr('placeholder')});
	} catch(e) {}


	//and add form reset functionality
	$('#id-message-form').on('reset', function(){
		$('.message-form .message-body').empty();
		
		$('.message-form .ace-file-input:not(:first-child)').remove();
		$('.message-form input[type=file]').ace_file_input('reset_input_ui');

		var val = tag_input.data('value');
		tag_input.parent().find('.tag').remove();
		$(val.split(',')).each(function(k,v){
			tag_input.before('<span class="tag">'+v+'<button class="close" type="button">&times;</button></span>');
		});
	});
	*/
	
});

/**
 * 修改附件下载次数
 */
function setDownloadCount(id, count){
	$.ajax({
		url: '/admin/sys/attachment/setDownloadCounts',
		data: {
			"id": id,
			"count": parseInt(count)+1
		},
		type: 'POST',
		dataType: 'JSON',
		success: function(){
			
		}
	});
}

/**
 * 输入数字回车后跳转到相应页面
 * @returns
 */ 
function goToPage(){
	if(event.keyCode == 13){
		var num = $('#page-num-go-to').val();
		window.location = '/admin/tools/emails/list?pageNum=' + num;
	}
}

/**
 * 点击打开写邮件tab并发送邮件
 * @returns
 */
$('#send-email-btn').bind('click', function(){
	//添加加载中的提示
	$('.page-content').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-160"></i></div>');

	var formData = new FormData();
	formData.append("toUsername", $('#form-field-recipient').val());
	formData.append("subject", $('#form-field-subject').val());
	formData.append("content", $('.wysiwyg-editor').html());
	var attachments = document.getElementsByClassName("attachment[]");
	//循环添加多个附件，后台用MultipartFile[]或者List<MultipartFile>接收
	for(var i = 0; i < attachments.length; i++){
		formData.append('file', attachments[i].files[0]);
	}
	
	$.ajax({
		url: '/admin/tools/emails/send',
		data: formData,
		type: 'post',
		dataType: 'json',
		contentType:false,
		processData: false,
		async: true,//如果是false的话，上方添加加载中的图标会无法显示
		success: function(obj){
			if(obj.status == 200){
				$('.message-loading-overlay').remove();
				gritterSuccess(obj.data);
				//$('.btn-back-message-list').trigger('click');
				location.reload();//刷新当前页面
			}else{
				$('.message-loading-overlay').remove();
				gritterError(obj.msg);
			}
		},
		error: function(){
			gritterError(info.noAuth);
		}
	});
});

